/*
 *    Copyright (c) 2018-2025, haohanwork.com All rights reserved.
 */
package com.haohan.cloud.scm.goods.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haohan.cloud.scm.api.goods.dto.PlatformPriceSqlDTO;
import com.haohan.cloud.scm.api.goods.entity.PlatformGoodsPrice;
import com.haohan.cloud.scm.goods.mapper.PlatformGoodsPriceMapper;
import com.haohan.cloud.scm.goods.service.PlatformGoodsPriceService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 平台商品定价
 *
 * @author haohan
 * @date 2019-05-13 20:38:26
 */
@Service
public class PlatformGoodsPriceServiceImpl extends ServiceImpl<PlatformGoodsPriceMapper, PlatformGoodsPrice> implements PlatformGoodsPriceService {

    /**
     * 查询平台定价列表
     *
     * @param query 必须 pricingPmId、merchantId、queryDate、goodsIds或goodsId
     * @return
     */
    @Override
    public List<PlatformGoodsPrice> fetchListByDate(PlatformPriceSqlDTO query) {
        return baseMapper.selectList(Wrappers.<PlatformGoodsPrice>query().lambda()
                .eq(PlatformGoodsPrice::getPmId, query.getPricingPmId())
                .eq(PlatformGoodsPrice::getMerchantId, query.getMerchantId())
                .apply("{0} between start_date and end_date", query.getQueryDate())
                .in(CollUtil.isNotEmpty(query.getGoodsIds()), PlatformGoodsPrice::getGoodsId, query.getGoodsIds())
                .eq(StrUtil.isNotEmpty(query.getGoodsId()), PlatformGoodsPrice::getGoodsId, query.getGoodsId())
                .orderByDesc(PlatformGoodsPrice::getUpdateDate)
        );
    }

    /**
     * 查询平台定价
     * 同一时间段内 一个商家下 商品规格只有一个定价
     *
     * @param query 必须 pricingPmId、merchantId、queryDate、modelId
     * @return
     */
    @Override
    public PlatformGoodsPrice fetchOneByDate(PlatformPriceSqlDTO query) {
        return baseMapper.selectList(Wrappers.<PlatformGoodsPrice>query().lambda()
                .eq(PlatformGoodsPrice::getPmId, query.getPricingPmId())
                .eq(PlatformGoodsPrice::getMerchantId, query.getMerchantId())
                .apply("{0} between start_date and end_date", query.getQueryDate())
                .eq(PlatformGoodsPrice::getModelId, query.getModelId())
                .orderByDesc(PlatformGoodsPrice::getUpdateDate)
        ).stream().findFirst().orElse(null);
    }
}
